package app

import (
	"context"
	"flag"
	"os"
	"syscall"

	"rank/internal/store"

	"github.com/asim/go-micro/v3/config"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"golang.org/x/sync/errgroup"
)

const (
	serverName = "svr"

	logLevelKey = "loglevel"
	logLevelDef = "info"

	printVersionKey = "version"
	printVersionDef = false
)

func init() {
	// NOTE: go-micro 只支持小写字母的选项
	flag.String(logLevelKey, logLevelDef, "log level")
	flag.Bool(printVersionKey, printVersionDef, "print program build version")

	flag.Parse()
}

// App ...
type App interface {
	Run(chan<- os.Signal) error
	Stop() error
}

// New ...
func New(options ...Option) (App, error) {
	svc := &app{ctx: context.Background()}
	for _, opt := range options {
		if err := opt(svc); err != nil {
			return nil, err
		}
	}

	return svc, nil
}

type app struct {
	ginRouter *gin.Engine
	conf      config.Config
	redisCli  redis.UniversalClient
	dao       store.Dao
	ctx       context.Context
}

// Run ...
func (a *app) Run(ch chan<- os.Signal) error {
	g, _ := errgroup.WithContext(a.ctx)
	g.Go(func() error {
		if a.ginRouter == nil {
			return nil
		}

		if err := a.ginRouter.Run(); err != nil {
			return err
		}
		return nil
	})

	if err := g.Wait(); err != nil {
		ch <- syscall.SIGQUIT
		return err
	}
	return nil
}

// Stop ...
func (a *app) Stop() error {
	return nil
}
